#include "transparentoverlay.h"
#include "ui_transparentoverlay.h"

TransparentOverlay::TransparentOverlay(QMediaPlayer *player,QStackedWidget *StackedWidget, QLabel *ImageLabel, QVideoWidget *VideoWidget, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::TransparentOverlay)
{
    ui->setupUi(this);
    //setAttribute(Qt::WA_TranslucentBackground, true);
    //setWindowFlags(Qt::FramelessWindowHint);

    currentFileIndex = 0;
    currentImageFileIndex = 0;
    currentVideoFileIndex = 0;

    this->player = player;
    this->imageLabel = ImageLabel;
    this->videoWidget = VideoWidget;
    this->stackedWidget = StackedWidget;

    ui->back->setIcon(QIcon(":/icon/pre.svg"));
    ui->play->setIcon(QIcon(":/icon/pause.svg"));
    ui->next->setIcon(QIcon(":/icon/next.svg"));

    ui->lineEdit->setText("选择默认路径可不设置");

    QPixmap pixmap(":/icon/settingS.svg");
    ui->settingIcon->setPixmap(pixmap);

    KeyTriggerSystem();

    //default path
    filePath = QDir::currentPath()+"/video/";
    updateVideoPlayList(filePath);

    ui->listWidget->setDragEnabled(true);
    ui->listWidget->setDragDropMode(QAbstractItemView::InternalMove);

    //默认radio
    ui->radioButton_5->setChecked(true);
    ui->radioButton_4->setChecked(true);
    playMode = PlayMode::LISTLOOP;
    showMode = ShowMode::IMAGEVIEW;

    defaultBackground();

    radioButtonConnect();

    // 创建定时器对象
    imageTimer = new QTimer(this);
    imageTimer->setInterval(1000);
    ui->spinBox->setValue(1);
    // 连接定时器的 timeout 信号到自定义的槽函数
    connect(imageTimer, &QTimer::timeout, this, &TransparentOverlay::onTimeout);
    connect(ui->listWidget, &QListWidget::currentRowChanged, this, &TransparentOverlay::onItemMoved);
    connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, &TransparentOverlay::playSelectItem);
    connect(player,&QMediaPlayer::mediaStatusChanged, this, playPlanFunc);


    //TCP UDP
    TcpServer* server = new TcpServer(this);
    if (!server->listen(QHostAddress::Any, 15456))
    {
        qDebug() << "Server could not start";
    }

    //TCP UDP connect
    connect(server,&TcpServer::newMessage,this,&TransparentOverlay::messageUpdate);

}

TransparentOverlay::~TransparentOverlay()
{
    delete ui;
}

void TransparentOverlay::messageUpdate(QString message)
{
    if (message == "PLAY" || message == "PAUSE")
    {
         on_play_clicked();
    }
    if (message == "S")
    {
         videoStopDefaultImage();
    }
    if (message == "U+")
    {
        on_next_clicked();
    }
    if (message == "U-")
    {
        on_back_clicked();
    }
    if (message == "V+")
    {

    }
    if (message == "V-")
    {

    }
    if (message == "P-")
    {
        on_back_clicked();
    }
    if (message == "P+")
    {
        on_next_clicked();
    }

    if (message.contains("U|"))
    {
        showMode = ShowMode::VIDEOVIEW;

        QStringList fullList = message.split(",");
        QStringList fileNameList = fullList.at(0).split("|");
        QString filePathChild = fileNameList.at(1);
        QString fileName = fullList.at(1);
        tcpCmdSelect(filePathChild,fileName);
    }

    if (message.contains("P|"))
    {
        showMode = ShowMode::IMAGEVIEW;
        QStringList fullList = message.split(",");
        QStringList fileNameList = fullList.at(0).split("|");
        QString filePathChild = fileNameList.at(1);
        QString fileName = fullList.at(1);
        tcpCmdSelect(filePathChild,fileName);
    }
}



void TransparentOverlay::tcpCmdSelect(QString filePathChild, QString fileName)
{

    currentFilePath = QDir::currentPath()+"/video/"  +filePathChild +"/" + fileName;
    qDebug() << "currentFilePath:" << currentFilePath;
    QString updatePath = QDir::currentPath()+"/video/"  +filePathChild +"/";
    filePath = updatePath;
    qDebug() << "filePath:" << filePath;

    //更新播放列表
    tcpCmdUpdate(updatePath);

    if (showMode == ShowMode::IMAGEVIEW)
    {
        qDebug()<<"地址1：" << currentFilePath;
        imageTimer->stop();
        imageLoading();
    }
    else if (showMode == ShowMode::VIDEOVIEW)
    {
        qDebug()<<"地址1：" << currentFilePath;
        player->setSource(QUrl::fromLocalFile(QDir::currentPath()+"/video/"  +filePathChild +"/" + fileName));
        player->play();
    }
    else if (showMode == ShowMode::MIXMODE)
    {

    }
}

void TransparentOverlay::playPlanFunc(QMediaPlayer::MediaStatus status)
{
    if (status == QMediaPlayer::EndOfMedia && (currentVideoFileIndex < videoFiles.size()) )
    {
        if (playMode == PlayMode::LISTLOOP )
        {
            if(videoFiles.size() == 1 || (currentVideoFileIndex == (videoFiles.size()-1)))
            {
                currentVideoFileIndex = 0;
            }
            else
            {
                currentVideoFileIndex++;
            }
            currentFilePath = filePath + videoFiles.at(currentVideoFileIndex);
            videoLoading();
        }
        else if (playMode == PlayMode::LISTLOOPONCE)
        {
            if (currentVideoFileIndex < videoFiles.size())
            {
                currentVideoFileIndex++;
            }
            else
            {
                currentVideoFileIndex = 0;
                //自动进入图片模式
                player->pause();
            }
        }
        else if (playMode == PlayMode::SIGNELLOOPONCE)
        {
            //current 不变
            player->pause();
        }
        else if(playMode == PlayMode::SINGELLOOP)
        {
            videoLoading();
        }
    }
    if (currentVideoFileIndex == videoFiles.size())
    {
        currentVideoFileIndex = 0;
    }
}

void TransparentOverlay::updatePlayingState(QString fileName)
{
    for (int i = 0; i < ui->listWidget->count();i++)
    {
        if (ui->listWidget->item(i)->text() == fileName)
        {
            ui->listWidget->item(i)->setIcon(QIcon(":/icon/choose.svg"));
        }
        else
        {
            ui->listWidget->item(i)->setIcon(QIcon(""));
        }
    }
}

void TransparentOverlay::radioButtonConnect()
{
    connect(ui->radioButton,   &QRadioButton::toggled, this, &TransparentOverlay::onRadioButtonVideoModelToggled);
    connect(ui->radioButton_2, &QRadioButton::toggled, this, &TransparentOverlay::onRadioButtonVideoModelToggled);
    connect(ui->radioButton_3, &QRadioButton::toggled, this, &TransparentOverlay::onRadioButtonVideoModelToggled);
    connect(ui->radioButton_4, &QRadioButton::toggled, this, &TransparentOverlay::onRadioButtonVideoModelToggled);
    connect(ui->radioButton_5, &QRadioButton::toggled, this, &TransparentOverlay::onRadioButtonModelToggled);
    connect(ui->radioButton_6, &QRadioButton::toggled, this, &TransparentOverlay::onRadioButtonModelToggled);
    connect(ui->radioButton_7, &QRadioButton::toggled, this, &TransparentOverlay::onRadioButtonModelToggled);
}

void TransparentOverlay::onRadioButtonModelToggled(bool checked)
{
    qDebug()<<"onRadioButtonModelToggled image path:" << filePath;
    QRadioButton *sender = qobject_cast<QRadioButton *>(QObject::sender());
    if (sender) {
        qDebug() << sender->text() << " A is " << (checked? "checked" : "unchecked");
        if (checked == true)
        {
            if (sender->text() == "图片模式")
            {
                //图片模式
                showMode = ShowMode::IMAGEVIEW;
                updateImagePlayList(filePath);
                imageTimer->start();
            }
            else if(sender->text() == "视频模式")
            {
                //视频模式
                showMode = ShowMode::VIDEOVIEW;
                updateVideoPlayList(filePath);
                imageTimer->stop();
            }
            else if(sender->text() == "混合模式")
            {
                //混合模式
                showMode = ShowMode::MIXMODE;
            }
        }
    }
}
void TransparentOverlay::onRadioButtonVideoModelToggled(bool checked)
{
    QRadioButton *sender = qobject_cast<QRadioButton *>(QObject::sender());
    if (sender) {
        qDebug() << sender->text() << " B is " << (checked? "checked" : "unchecked");
        if (checked == true)
        {
            if (sender->text() == "单个播放一次")
            {
                //单个播放一次
                playMode = PlayMode::SIGNELLOOPONCE;
                imageTimer->stop();
            }
            else if(sender->text() == "列表循环一次")
            {
                //列表循环一次
                playMode = PlayMode::LISTLOOPONCE;
                imageTimer->start();
            }
            else if(sender->text() == "单个循环")
            {
                //单个循环
                playMode = PlayMode::SINGELLOOP;
                imageTimer->stop();
            }
            else if(sender->text() == "列表循环")
            {
                //列表循环
                playMode = PlayMode::LISTLOOP;
                imageTimer->start();
            }
        }
    }
}

//关闭视频窗口展示图片
void TransparentOverlay::closeVideoWindow()
{
    player->stop();
    this->stackedWidget->setCurrentWidget(this->imageLabel);
}

//关闭图片窗口打开视频窗口
void TransparentOverlay::closeImageWindow()
{
    this->stackedWidget->setCurrentWidget(this->videoWidget);
}


void TransparentOverlay::playSelectItem(QListWidgetItem *item)
{
    currentFilePath = filePath + item->text();

    if (showMode == ShowMode::IMAGEVIEW)
    {
        imageTimer->stop();
        imageLoading();
        for (int i = 0; i < ui->listWidget->count();i++)
        {
            ui->listWidget->item(i)->setIcon(QIcon(""));
        }
        for (int j = 0; j < ImageFiles.size(); j++)
        {
            if( item->text() == ImageFiles.at(j))
            {
                currentImageFileIndex = j;
                qDebug() << "currentImageFileIndex: " << j;
            }
        }
        item->setIcon(QIcon(":/icon/choose.svg"));
    }
    else if (showMode == ShowMode::VIDEOVIEW)
    {
        videoLoading();
    }
    else if (showMode == ShowMode::MIXMODE)
    {

    }
}

void TransparentOverlay::onItemMoved()
{
    // 清空播放列表
    videoFiles.clear();
    for (int i = 0; i < ui->listWidget->count(); ++i)
    {
        QListWidgetItem *item =  ui->listWidget->item(i);
        if (item)
        {
            QString text = item->text();
            videoFiles.append(text);
        }
    }
    qDebug() << "List: " << videoFiles;

    ui->pushButton_3->setStyleSheet("QPushButton {};");

}

void TransparentOverlay::KeyTriggerSystem()
{
    // 定义 Alt + A 快捷键
    QShortcut *shortcutESC = new QShortcut(QKeySequence(Qt::Key_Escape), this);
    connect(shortcutESC, &QShortcut::activated, this, &TransparentOverlay::onESCPressed);
}

void TransparentOverlay::updateVideoPlayList(QString folderPath)
{
    //clear
    ui->listWidget->clear();
    videoFiles.clear();

    closeImageWindow();

    QDir dir(folderPath);
    QStringList filters;
    filters << "*.mp4" << "*.avi" << "*.mkv" << "*.webm"; // 可根据需要添加更多视频格式
    videoFiles = dir.entryList(filters, QDir::Files);
    ui->listWidget->addItems(videoFiles);

    if (videoFiles.size() != 0)
    {
        currentFilePath = folderPath + videoFiles.at(currentVideoFileIndex);
        videoLoading();
    }
    else
    {
        qDebug()<< "目标目录没有文件";
        player->stop();
        ui->listWidget->addItem("目标目录没有文件");
        defaultBackground();
    }

}

void TransparentOverlay::updateImagePlayList(QString folderPath)
{
    //clear
    ui->listWidget->clear();
    ImageFiles.clear();

    closeVideoWindow();

    QDir dir(folderPath);
    QStringList filters;
    filters << "*.jpg" << "*.png" << ".PNG" << "*.JPEG" << "*.webp"; // 可根据需要添加更多视频格式
    ImageFiles = dir.entryList(filters, QDir::Files);
    ui->listWidget->addItems(ImageFiles);

    if (ImageFiles.size() != 0)
    {
        //currentFilePath = folderPath + ImageFiles.at(currentImageFileIndex);
        //imageLoading();
    }
    else
    {
        //
        defaultBackground();
        qDebug()<< "目标目录没有文件";
        ui->listWidget->addItem("目标目录没有文件");
        currentImageFileIndex = 0;
    }

}

void TransparentOverlay::imageLoading()
{
    QPixmap pixmap(currentFilePath);
    qDebug()<<"地址：" << currentFilePath;
    if (!pixmap.isNull())
    {
        qDebug() << "图片加载成功！宽度：" << pixmap.width() << "高度：" << pixmap.height();
    }
    else {
        qDebug() << "图片加载失败！";
    }

    // 图片缩放到与 label 大小相匹配，并保持宽高比
    pixmap = pixmap.scaled(imageLabel->size(), Qt::KeepAspectRatio);
    imageLabel->setScaledContents(true);

    imageLabel->setPixmap(pixmap);
    imageLabel->setAutoFillBackground(true);
    updatePlayingState(ImageFiles.at(currentImageFileIndex));
}

void TransparentOverlay::defaultBackground()
{
    this->stackedWidget->setCurrentWidget(this->imageLabel);
    QPixmap pixmap(QDir::currentPath()+"/resource/backgroung.jpg");
    if (!pixmap.isNull())
    {
        qDebug() << "图片加载成功！宽度：" << pixmap.width() << "高度：" << pixmap.height();
    }
    else {
        qDebug() << "图片加载失败！";
    }

    // 图片缩放到与 label 大小相匹配，并保持宽高比
    pixmap = pixmap.scaled(imageLabel->size(), Qt::KeepAspectRatio);
    imageLabel->setScaledContents(true);

    imageLabel->setPixmap(pixmap);
    imageLabel->setAutoFillBackground(true);
}

void TransparentOverlay::videoLoading()
{
    player->setSource(QUrl::fromLocalFile(currentFilePath));
    player->play();
    isPlaying = true;
    updatePlayingState(videoFiles.at(currentVideoFileIndex));
}


void TransparentOverlay::onESCPressed() {
    this->setHidden(true);
}

void TransparentOverlay::on_play_clicked()
{
    if(playState== true)
    {
        ui->play->setIcon(QIcon(":/icon/pause.svg"));
        playState = false;
        player->play();
        imageTimer->start();
    }
    else
    {
        ui->play->setIcon(QIcon(":/icon/play1.svg"));
        playState = true;
        player->pause();
        imageTimer->stop();
    }

}

void TransparentOverlay::videoStopDefaultImage()
{
    ui->play->setIcon(QIcon(":/icon/pause.svg"));
    playState = false;
    player->stop();
    imageTimer->start();
    defaultBackground();
}

void TransparentOverlay::on_pushButton_2_clicked()
{
    // 获取所有窗口的列表
    QWidgetList allWidgets = QApplication::allWidgets();
    // 遍历列表并关闭每个窗口
    for (QWidget *widget : allWidgets) {
        widget->close();
    }
}


void TransparentOverlay::on_back_clicked()
{
    if(showMode == ShowMode::IMAGEVIEW)
    {
        if (currentImageFileIndex <= 0)
        {
            currentImageFileIndex = 0;
        }
        else
        {
            currentImageFileIndex--;
        }
        currentFilePath = filePath + ImageFiles.at(currentImageFileIndex);
        imageLoading();
    }
    else if(showMode == ShowMode::VIDEOVIEW)
    {
        if (currentVideoFileIndex <= 0)
        {
            currentVideoFileIndex = 0;
        }
        else
        {
            currentVideoFileIndex--;
        }
        videoLoading();
    }

}


void TransparentOverlay::on_pushButton_3_clicked()
{
    onItemMoved();
     ui->pushButton_3->setStyleSheet("QPushButton {background-color: green};");
}


void TransparentOverlay::on_pushButton_clicked()
{
    QString fileUrl = QFileDialog::getExistingDirectory(this,"选择目录",QString());
    if (!fileUrl.isEmpty())
    {
        ui->lineEdit->setText(fileUrl);
        filePath = fileUrl +"/";
        if (showMode == ShowMode::IMAGEVIEW)
        {
            updateImagePlayList(filePath);
        }
        else if(showMode == ShowMode::VIDEOVIEW)
        {
            updateVideoPlayList(filePath);
        }
        else if(showMode == ShowMode::MIXMODE)
        {

        }
    }
}

void TransparentOverlay::tcpCmdUpdate(QString fileUrl)
{

        ui->lineEdit->setText(fileUrl);
        if (showMode == ShowMode::IMAGEVIEW)
        {
            updateImagePlayList(fileUrl);
        }
        else if(showMode == ShowMode::VIDEOVIEW)
        {
            updateVideoPlayList(fileUrl);
        }
        else if(showMode == ShowMode::MIXMODE)
        {

        }
}

void TransparentOverlay::onTimeout()
{
    if ((showMode  == ShowMode::IMAGEVIEW) && (ImageFiles.size() > 0))
    {
        //next image
        if (playMode == PlayMode::LISTLOOP )
        {
            if(ImageFiles.size() == 1 || (currentImageFileIndex == (ImageFiles.size()-1)))
            {
                currentImageFileIndex = 0;
            }
            else
            {
                currentImageFileIndex++;
            }
            qDebug() << "currentPath" << currentImageFileIndex;
            currentFilePath = filePath + ImageFiles.at(currentImageFileIndex);
            imageLoading();
        }
        else if (playMode == PlayMode::LISTLOOPONCE)
        {
            if (currentImageFileIndex < (ImageFiles.size()-1))
            {
                currentImageFileIndex++;
            }
            else if(currentImageFileIndex == (ImageFiles.size()-1))
            {
                return;
            }
            currentFilePath = filePath + ImageFiles.at(currentImageFileIndex);
            imageLoading();
        }
        else if (playMode == PlayMode::SIGNELLOOPONCE)
        {
            currentFilePath = filePath + ImageFiles.at(currentImageFileIndex);
            imageLoading();
        }
        else if(playMode == PlayMode::SINGELLOOP)
        {
            //
            currentFilePath = filePath + ImageFiles.at(currentImageFileIndex);
            imageLoading();
        }
    }
}


void TransparentOverlay::on_spinBox_valueChanged(int arg1)
{
    qDebug()<<"image time:" << arg1;
    imageTimer->setInterval(arg1*1000);
}


void TransparentOverlay::on_next_clicked()
{
    if(showMode == ShowMode::IMAGEVIEW)
    {
        if (currentImageFileIndex == (ImageFiles.size()-1))
        {
            currentImageFileIndex = 0;
        }
        else
        {
            currentImageFileIndex++;
        }
        currentFilePath = filePath + ImageFiles.at(currentImageFileIndex);
        imageLoading();
    }
    else if(showMode == ShowMode::VIDEOVIEW)
    {
        if (currentVideoFileIndex == (videoFiles.size()-1))
        {
            currentVideoFileIndex = 0;
        }
        else
        {
            currentVideoFileIndex++;
        }
        videoLoading();
    }

}

